<script setup lang="ts">
    import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
    import echarts, { EChartsOption } from '@/utils/lib/echarts'
    
    // 定义 props
    const props = defineProps<{
      option: EChartsOption
      theme?: string | object
    }>()
    
    // 图表容器引用
    const chartDom = ref<HTMLDivElement>()
    // 图表实例
    const chartInstance = ref<echarts.ECharts>()
    
    // 初始化图表
    const initChart = () => {
      if (!chartDom.value) return
      
      // 创建图表实例
      chartInstance.value = echarts.init(chartDom.value, props.theme)
      // 设置配置项
      chartInstance.value.setOption(props.option)
    }
    
    // 监听窗口变化
    const resizeObserver = new ResizeObserver(() => {
      // chartInstance.value?.resize()
    })
    
    onMounted(() => {
      initChart()
      if (chartDom.value) {
        resizeObserver.observe(chartDom.value)
      }
    })
    
    onBeforeUnmount(() => {
      resizeObserver.disconnect()
      chartInstance.value?.dispose()
    })
    
    // 监听 option 变化
    watch(() => props.option, (newOption) => {
      chartInstance.value?.setOption(newOption)
    }, { deep: true })
    
    // 主题变化处理
    watch(() => props.theme, (newTheme) => {
      const option = chartInstance.value?.getOption()
      chartInstance.value?.dispose()
      chartInstance.value = echarts.init(chartDom.value!, newTheme)
      chartInstance.value.setOption(option!)
    })
    </script>
    
    <template>
      <div class="echarts-container">
        <div ref="chartDom" class="echarts-canvas"></div>
      </div>
    </template>
    
    <style scoped>
    .echarts-container {
      width: 100%;
      height: 100%;
    }
    .echarts-canvas {
      width: 100%;
      height: 100%;
      min-height: 200px;
    }
    </style>